<template>
	<up-cell-group class="peak-valley-time-setting-item" :border="false">
		<up-cell :title="name" :arrow="false">
			<template #right-icon>
				<image class="close-icon" src="/static/site-params-settings/close-icon.png" mode="aspectFill"
					@tap="handleRemove"></image>
			</template>
		</up-cell>
		<up-cell isLink :title="$t('peak-valley-time-setting.item.cell-1')" name="startTime" @click="handleCellClick">
			<template #value>
				<up-input :modelValue="localModel.startTime" readonly class="readonly" border="none" inputAlign="right"
					:placeholder="$t('peak-valley-time-setting.item.cell-1.placeholder')"></up-input>
			</template>
		</up-cell>
		<up-cell isLink :title="$t('peak-valley-time-setting.item.cell-2')" name="endTime" @click="handleCellClick">
			<template #value>
				<up-input :modelValue="localModel.endTime" readonly class="readonly" border="none" inputAlign="right"
					:placeholder="$t('peak-valley-time-setting.item.cell-2.placeholder')"></up-input>
			</template>
		</up-cell>
		<up-cell isLink :title="$t('peak-valley-time-setting.item.cell-3')" name="periodType" @click="handleCellClick">
			<template #value>
				<up-input :modelValue="localModel.periodTypeLabel" readonly class="readonly" border="none"
					inputAlign="right" :placeholder="$t('peak-valley-time-setting.item.cell-3.placeholder')"></up-input>
			</template>
		</up-cell>
		<up-cell v-show="!localModel.discharge" :title="$t('peak-valley-time-setting.item.cell-4')">
			<template #value>
				<up-input disabledColor="rgba(0,0,0,0)" v-model="localModel.charge" border="none" type="digit"
					inputAlign="right" :placeholder="$t('peak-valley-time-setting.item.cell-4.placeholder')"
					@change="handleCharge"></up-input>
			</template>
		</up-cell>
		<up-cell v-show="!localModel.charge" :title="$t('peak-valley-time-setting.item.cell-5')">
			<template #value>
				<up-input disabledColor="rgba(0,0,0,0)" v-model="localModel.discharge" border="none" type="digit"
					inputAlign="right" :placeholder="$t('peak-valley-time-setting.item.cell-5.placeholder')"
					@change="handleDisharge"></up-input>
			</template>
		</up-cell>

		<up-datetime-picker ref="datetimePicker" v-model="currentTime" closeOnClickOverlay
			:confirm-text="$t('time.confirm')" :filter="timeFilter" :cancel-text="$t('time.cancel')"
			:title="$t('peak-valley-time-setting.date.picker.title')" :show="showTime" mode="time"
			@confirm="handleTimeChange" @cancel="closeTimePicker" @close="closeTimePicker">
		</up-datetime-picker>
		<up-picker ref="statusPickers" :show="showStatus" :title="$t('peak-valley-time-setting.types.picker.title')"
			:confirm-text="$t('time.confirm')" :cancel-text="$t('time.cancel')" closeOnClickOverlay
			:columns="statusColumns" @close="showStatus = false" @cancel="showStatus = false"
			@confirm="handleStatusChange">
		</up-picker>
	</up-cell-group>
</template>

<script setup>
	import {
		computed,
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		useI18n
	} from "vue-i18n";
	const {
		t
	} = useI18n();
	const model = defineModel({
		type: Object
	})

	const {
		disbaleTimeArea
	} = defineProps({
		name: String,
		disbaleTimeArea: {
			type: Array,
			default: () => []
		}
	})

	const showTime = ref(false);
	const showStatus = ref(false);
	const statusPicker = ref(null);
	const currentTime = ref(null);
	const showTimeType = ref(null);
	const emits = defineEmits(['remove'])
	const localModel = reactive({
		startTime: '',
		endTime: '',
		periodTypeLabel: '',
		periodType: '',
		charge: '',
		discharge: ''
	})
	const statusColumns = computed(() => [
		[{
				text: t('peak-valley-time-setting.type-1'),
				value: 4
			},
			{
				text: t('peak-valley-time-setting.type-2'),
				value: 3
			},
			{
				text: t('peak-valley-time-setting.type-3'),
				value: 2
			},
			{
				text: t('peak-valley-time-setting.type-4'),
				value: 1
			},
			{
				text: t('peak-valley-time-setting.type-5'),
				value: 5
			},
		]
	]);
	const datetimePicker = ref(null)
	const timeFilter = (type, values) => {
		if (type === 'hour') {
			return values.filter((hour) => {
				const currentHour = parseInt(hour);
				for (const disabledTime of disbaleTimeArea) {
					const startHour = parseInt(disabledTime.start.split(':')[0]);
					const endHour = parseInt(disabledTime.end.split(':')[0]);
					if (currentHour >= startHour && currentHour < endHour) {
						return false;
					}
				}
				return true;
			});
		} else if (type === 'minute') {
			const currentHour = getCurrentHour();
			return values.filter((minute) => {
				const currentMinute = parseInt(minute);
				for (const disabledTime of disbaleTimeArea) {
					const startHour = parseInt(disabledTime.start.split(':')[0]);
					const startMinute = parseInt(disabledTime.start.split(':')[1]);
					const endHour = parseInt(disabledTime.end.split(':')[0]);
					const endMinute = parseInt(disabledTime.end.split(':')[1]);
					if (currentHour === startHour && currentMinute >= startMinute) {
						return false;
					}
					if (currentHour === endHour && currentMinute < endMinute) {
						return false;
					}
				}
				return true;
			});
		}
		return values;
	}

	const getCurrentHour = () => {
		const picker = datetimePicker.value?.$refs?.picker;
		if (picker) {
			const values = picker.getValues();
			return parseInt(values?.[0] || 0);
		}
		return 0;
	}

	const handleRemove = () => {
		emits('remove');
	}

	const handleCellClick = ({
		name
	}) => {
		if (['startTime', 'endTime'].includes(name)) {
			currentTime.value = localModel?.[name];
			showTimeType.value = name;
			showTime.value = true;
		} else if (name === 'periodType') {
			showStatus.value = true;
			const idx = statusColumns.value[0].findIndex(item => item.value === localModel.periodType);
			if (idx != -1) {
				statusPicker.value?.setColumnValues(0, idx)
			}
		}
	}

	const closeTimePicker = () => {
		showTimeType.value = null;
		showTime.value = false;
	}

	const handleTimeChange = ({
		value
	}) => {
		currentTime.value = value;
		if (showTimeType.value) {
			localModel[showTimeType.value] = value;
			model.value[showTimeType.value] = value;

		}
		closeTimePicker();
	}

	const handleStatusChange = ({
		value
	}) => {
		const [period] = value;
		localModel.periodType = period.value;
		localModel.periodTypeLabel = period.text;
		model.value.periodType = period.value;
		showStatus.value = false;
	}

	const handleCharge = (value) => {
		localModel.charge = value;
		model.value.controlPower = Number(value);
	}

	const handleDisharge = (value) => {
		localModel.discharge = value;
		model.value.controlPower = -Number(value);
	}

	watch(() => model.value, (now) => {
		localModel.startTime = now.startTime;
		localModel.endTime = now.endTime;
		localModel.periodType = now.periodType;
		localModel.periodTypeLabel = statusColumns.value[0].find(item => Number(item.value) === now.periodType)
			?.text;
		const controlPower = Math.abs(now.controlPower) || "";
		if (now.controlPower > 0) {
			localModel.charge = controlPower;
		} else {
			localModel.discharge = controlPower;
		}
	}, {
		immediate: true
	})
</script>

<style lang="scss">
	.peak-valley-time-setting-item {
		.close-icon {
			width: 40rpx;
			height: 40rpx;
			display: block;
		}

		& :deep(.u-input.readonly) {
			pointer-events: none;
		}
	}

	.toolbar-right-close {
		margin-right: 24rpx;

		& :deep(.u-icon__icon) {
			font-size: 26rpx;
			color: #fff !important;
		}
	}
</style>